import React from "react";
import { useLocation, Link } from "react-router-dom";
import { Space, Breadcrumb } from "antd";
import menus from "@/routers";
export default function AppBreadCrumb() {
  const breadcrumbNameMap = {};
  const location = useLocation();

  const getBreadCrumb = (menus) => {
    menus.forEach((menu) => {
      if (menu.children) {
        breadcrumbNameMap[menu?.key] = menu?.label;
        getBreadCrumb(menu.children);
      } else {
        breadcrumbNameMap[menu?.key] = menu?.label;
      }
    });
  };

  getBreadCrumb(menus);



  const pathSnippets = location.pathname.split("/").filter((i) =>i);
  const extraBreadcrumbItems = pathSnippets.map((_, index) => {
    const url = `/${pathSnippets.slice(0, index + 1).join("/")}`;

    // 判断breadcrumbNameMap[url] 是否为undefined,是的话就返回空对象
    return breadcrumbNameMap[url]
      ? {
          key: url,
          title: <Link to={url}>{breadcrumbNameMap[url]}</Link>,
        }
      : {};
  });
  const breadcrumbItems = [
    {
      title: <Link to="/">主页</Link>,
      key: "home",
    },
  ].concat(extraBreadcrumbItems);
  return (
    <Space>
      <Breadcrumb items={breadcrumbItems} />
    </Space>
  );
}
